package com.ibm.testbed.script.util;

import org.eclipse.jface.viewers.ColumnViewer;
import org.eclipse.jface.viewers.StyledCellLabelProvider;
import org.eclipse.jface.viewers.ViewerCell;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.widgets.Display;

public class FileCellLabelProvider extends StyledCellLabelProvider {

	private int index = 0;
	private ColumnViewer viewer;

	public FileCellLabelProvider(ColumnViewer viewer,int index) {
		this.viewer = viewer;
		this.index = index;
	}

	private static final String key = "Edit Delete";

	/**
	 * highlight the key string in the cell
	 * @param cell
	 * @return
	 */
	private void highLightKeys(ViewerCell cell,String key) {
		String cellText = cell.getText();
		if(!cellText.equalsIgnoreCase(key)){
			return;
		}
//		int[] indexs = getIndexs(key, cellText);
		int[] indexs = {0,5};
//		int keyLength = key.length();
		Color bgColor = Display.getDefault().getSystemColor(
				SWT.COLOR_BLUE);
		StyleRange[] srs = new StyleRange[indexs.length];
		for (int i = 0; i < indexs.length; i++) {
			StyleRange sr = new StyleRange();
			sr.start = indexs[i];
			if(i == 0){
				sr.length = 4;
			}else{
				sr.length = 6;
			}
			sr.underline = true;
			sr.underlineColor = bgColor;
			sr.background = Display.getDefault().getSystemColor(
					SWT.COLOR_GRAY);
			srs[i] = sr;
		}
		cell.setStyleRanges(srs);
		
	}

	/**
	 * search the searchedText and get all indexes of key in the text
	 * @param key
	 * @param searchedText
	 * @return index[]
	 */
	private int[] getIndexs(String key, String searchedText) {
		int keyLength = key.length();
		int[] indexes = new int[searchedText.length() / keyLength + 1];
		for (int i = 0; i < indexes.length; i++) {
			indexes[i] = -1;
		}
		int index = -keyLength;
		int i = 0;
		while (index != -1) {
			index = searchedText.indexOf(key, index + keyLength);
			indexes[i++] = index;
		}
		int[] result = new int[--i];
		System.arraycopy(indexes, 0, result, 0, result.length);
		return result;
	}
	
	
	public void update(ViewerCell cell) {
		Object element = cell.getElement();
		if (element instanceof String[]) {
			switch (index) {
			case 0:
				cell.setText(((String[]) element)[0]);
				break;
			case 1:
				cell.setText(((String[]) element)[1]);
				break;
			case 2:
				cell.setText(((String[]) element)[2]);
				break;
			case 3:
				cell.setText(((String[]) element)[3]);
				break;
			case 4:
				cell.setText(((String[]) element)[4]);
				break;
			case 5:
				cell.setText(((String[]) element)[5]);
				break;
			case 6:
				cell.setText(((String[]) element)[6]);
				break;
			case 7:
				cell.setText(((String[]) element)[7]);
				break;
			default:
				break;
			}
		}
	    highLightKeys(cell, key);
	}
}
